<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>资产管理系统</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
            color: #333;
        }

        h1 {
            color: #2c3e50;
            text-align: center;
            margin-bottom: 30px;
        }

        h2 {
            color: #34495e;
            border-bottom: 2px solid #3498db;
            padding-bottom: 10px;
            margin-top: 25px;
        }

        h3 {
            color: #2980b9;
        }

        .container {
            background-color: white;
            padding: 25px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
        }

        .section {
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }

        .section:last-child {
            border-bottom: none;
        }

        .form-group {
            margin-bottom: 15px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }

        input,
        textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
            font-size: 16px;
            transition: border-color 0.3s;
        }

        input:focus,
        textarea:focus {
            border-color: #3498db;
            outline: none;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }

        button {
            background-color: #3498db;
            color: white;
            padding: 12px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
            transition: background-color 0.3s;
            margin-top: 10px;
        }

        button:hover {
            background-color: #2980b9;
        }

        button:disabled {
            background-color: #95a5a6;
            cursor: not-allowed;
        }

        .error {
            color: #e74c3c;
            margin-top: 10px;
            padding: 10px;
            background-color: #fadbd8;
            border-radius: 4px;
            border-left: 4px solid #e74c3c;
        }

        .success {
            color: #27ae60;
            margin-top: 10px;
            padding: 10px;
            background-color: #d5f5e3;
            border-radius: 4px;
            border-left: 4px solid #27ae60;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        th,
        td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }

        th {
            background-color: #3498db;
            color: white;
        }

        tr:nth-child(even) {
            background-color: #f8f9fa;
        }

        tr:hover {
            background-color: #f1f4f7;
        }

        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
            margin-right: 10px;
            vertical-align: middle;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        .asset-list {
            margin-top: 30px;
        }

        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }

        .pagination button {
            margin: 0 5px;
            padding: 8px 12px;
            background-color: #f8f9fa;
            color: #3498db;
            border: 1px solid #ddd;
        }

        .pagination button.active {
            background-color: #3498db;
            color: white;
        }

        .pagination button:hover:not(.active) {
            background-color: #e9ecef;
        }
    </style>
</head>

<body>
    <h1>资产管理系统</h1>

    <div class="container">
        <!-- 创建资产部分 -->
        <div class="section">
            <h2>创建新资产</h2>
            <div class="form-group">
                <label for="create-id">资产ID:</label>
                <input type="text" id="create-id" required placeholder="请输入唯一标识符">
                <small>资产ID必须是唯一的字母数字组合</small>
            </div>
            <div class="form-group">
                <label for="create-owner">所有者:</label>
                <input type="text" id="create-owner" required placeholder="请输入所有者姓名">
            </div>
            <div class="form-group">
                <label for="create-name">资产名称:</label>
                <input type="text" id="create-name" required placeholder="请输入资产名称">
            </div>
            <div class="form-group">
                <label for="create-info">资产信息:</label>
                <textarea id="create-info" rows="3" placeholder="请输入资产详细信息"></textarea>
            </div>
            <button id="create-btn" onclick="createAsset()">创建资产</button>
            <div id="create-result" class="result"></div>
        </div>

        <!-- 查询资产部分 -->
        <div class="section">
            <h2>查询资产</h2>
            <div class="form-group">
                <label for="query-id">资产ID:</label>
                <input type="text" id="query-id" required placeholder="请输入要查询的资产ID">
            </div>
            <button id="query-btn" onclick="queryAsset()">查询资产</button>
            <div id="query-result" class="result"></div>
            <div id="asset-details" style="margin-top: 20px; display: none;">
                <h3>资产详情</h3>
                <table>
                    <tr>
                        <th>ID</th>
                        <td id="detail-id"></td>
                    </tr>
                    <tr>
                        <th>所有者</th>
                        <td id="detail-owner"></td>
                    </tr>
                    <tr>
                        <th>名称</th>
                        <td id="detail-name"></td>
                    </tr>
                    <tr>
                        <th>信息</th>
                        <td id="detail-info"></td>
                    </tr>
                </table>
            </div>
        </div>

        <!-- 转移资产部分 -->
        <div class="section">
            <h2>转移资产所有权</h2>
            <div class="form-group">
                <label for="transfer-id">资产ID:</label>
                <input type="text" id="transfer-id" required placeholder="请输入要转移的资产ID">
            </div>
            <div class="form-group">
                <label for="transfer-owner">新所有者:</label>
                <input type="text" id="transfer-owner" required placeholder="请输入新所有者姓名">
            </div>
            <button id="transfer-btn" onclick="transferAsset()">转移资产</button>
            <div id="transfer-result" class="result"></div>
        </div>

        <!-- 资产列表部分 -->
        <div class="section asset-list">
            <h2>所有资产列表</h2>
            <div id="list-controls">
                <button onclick="loadAssets(1)">刷新列表</button>
                <div id="list-info" style="margin-top: 10px;"></div>
            </div>
            <table id="assets-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>所有者</th>
                        <th>名称</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="assets-body">
                    <!-- 资产列表将在这里动态生成 -->
                </tbody>
            </table>
            <div id="pagination" class="pagination">
                <!-- 分页按钮将在这里动态生成 -->
            </div>
        </div>
    </div>

    <script>
        const API_BASE_URL = 'http://localhost:3000/api';
        let currentPage = 1;
        const itemsPerPage = 10;

        // 页面加载时获取资产列表
        document.addEventListener('DOMContentLoaded', function() {
            loadAssets(currentPage);
        });

        // 创建资产
        async function createAsset() {
            const id = document.getElementById('create-id').value.trim();
            const owner = document.getElementById('create-owner').value.trim();
            const name = document.getElementById('create-name').value.trim();
            const info = document.getElementById('create-info').value.trim();
            const createBtn = document.getElementById('create-btn');
            
            // 简单验证
            if (!id || !owner || !name) {
                showError('create-result', '所有带*号的字段都是必填的');
                return;
            }
            
            if (!/^[a-zA-Z0-9-_]+$/.test(id)) {
                showError('create-result', '资产ID只能包含字母、数字、-或_');
                return;
            }

            setLoadingState(createBtn, true);
            
            try {
                const response = await fetch(`${API_BASE_URL}/createAsset`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ id, owner, name, info })
                });

                const data = await response.json();

                if (data.success) {
                    showSuccess('create-result', data.message);
                    // 清空表单
                    document.getElementById('create-id').value = '';
                    document.getElementById('create-owner').value = '';
                    document.getElementById('create-name').value = '';
                    document.getElementById('create-info').value = '';
                    // 刷新列表
                    loadAssets(currentPage);
                } else {
                    showError('create-result', data.message || '创建资产失败');
                }
            } catch (error) {
                console.error('创建资产失败:', error);
                showError('create-result', '网络错误或服务不可用');
            } finally {
                setLoadingState(createBtn, false);
            }
        }
        
        // 查询资产
        async function queryAsset() {
            const id = document.getElementById('query-id').value.trim();
            const queryBtn = document.getElementById('query-btn');
            
            if (!id) {
                showError('query-result', '请输入资产ID');
                return;
            }

            setLoadingState(queryBtn, true);
            
            try {
                const response = await fetch(`${API_BASE_URL}/queryAsset`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ id })
                });

                const data = await response.json();

                if (data.success) {
                    const asset = data.data;
                    showSuccess('query-result', `找到资产 ${asset.id}`);
                    document.getElementById('detail-id').textContent = asset.id;
                    document.getElementById('detail-owner').textContent = asset.owner;
                    document.getElementById('detail-name').textContent = asset.name;
                    document.getElementById('detail-info').textContent = asset.info || '无';
                    document.getElementById('asset-details').style.display = 'block';
                } else {
                    showError('query-result', data.message || '未找到资产');
                    document.getElementById('asset-details').style.display = 'none';
                }
            } catch (error) {
                console.error('查询资产失败:', error);
                showError('query-result', '查询资产失败: ' + (error.message || '网络错误'));
                document.getElementById('asset-details').style.display = 'none';
            } finally {
                setLoadingState(queryBtn, false);
            }
        }

        // 转移资产
        async function transferAsset() {
            const id = document.getElementById('transfer-id').value.trim();
            const newOwner = document.getElementById('transfer-owner').value.trim();
            const transferBtn = document.getElementById('transfer-btn');
            
            if (!id || !newOwner) {
                showError('transfer-result', '请输入资产ID和新所有者');
                return;
            }

            setLoadingState(transferBtn, true);
            
            try {
                const response = await fetch(`${API_BASE_URL}/transferAsset`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ id, newOwner })
                });

                const data = await response.json();

                if (data.success) {
                    showSuccess('transfer-result', data.message);
                    // 清空表单
                    document.getElementById('transfer-id').value = '';
                    document.getElementById('transfer-owner').value = '';
                    // 刷新列表
                    loadAssets(currentPage);
                } else {
                    showError('transfer-result', data.message || '转移失败');
                }
            } catch (error) {
                console.error('转移资产失败:', error);
                showError('transfer-result', '转移资产失败: ' + (error.message || '网络错误'));
            } finally {
                setLoadingState(transferBtn, false);
            }
        }

        // 加载资产列表
        async function loadAssets(page) {
            currentPage = page;
            const listInfo = document.getElementById('list-info');
            const assetsBody = document.getElementById('assets-body');
            const pagination = document.getElementById('pagination');
            
            setLoadingState(document.getElementById('list-controls').querySelector('button'), true);
            
            try {
                const response = await fetch(`${API_BASE_URL}/queryAssets?page=${page}&limit=${itemsPerPage}`);
                const data = await response.json();
                
                if (data.success) {
                    const assets = data.data.assets || [];
                    const total = data.data.total || 0;
                    const totalPages = Math.ceil(total / itemsPerPage);
                    
                    // 更新列表信息
                    listInfo.textContent = `显示 ${(page - 1) * itemsPerPage + 1} 到 ${Math.min(page * itemsPerPage, total)} 条，共 ${total} 条记录`;
                    
                    // 清空表格
                    assetsBody.innerHTML = '';
                    
                    // 填充表格
                    if (assets.length === 0) {
                        assetsBody.innerHTML = `
                            <tr>
                                <td colspan="4" style="text-align: center;">没有找到资产记录</td>
                            </tr>
                        `;
                    } else {
                        assets.forEach(asset => {
                            const row = document.createElement('tr');
                            row.innerHTML = `
                                <td>${asset.id}</td>
                                <td>${asset.owner}</td>
                                <td>${asset.name}</td>
                                <td>
                                    <button onclick="queryAssetById('${asset.id}')">查看</button>
                                </td>
                            `;
                            assetsBody.appendChild(row);
                        });
                    }
                    
                    // 生成分页
                    generatePagination(totalPages, page);
                } else {
                    assetsBody.innerHTML = `
                        <tr>
                            <td colspan="4" style="text-align: center; color: red;">加载资产列表失败: ${data.message || '未知错误'}</td>
                        </tr>
                    `;
                    pagination.innerHTML = '';
                }
            } catch (error) {
                console.error('加载资产列表失败:', error);
                assetsBody.innerHTML = `
                    <tr>
                        <td colspan="4" style="text-align: center; color: red;">加载资产列表失败: ${error.message || '网络错误'}</td>
                    </tr>
                `;
                pagination.innerHTML = '';
            } finally {
                setLoadingState(document.getElementById('list-controls').querySelector('button'), false);
            }
        }
        
        // 生成分页
        function generatePagination(totalPages, currentPage) {
            const pagination = document.getElementById('pagination');
            pagination.innerHTML = '';
            
            if (totalPages <= 1) return;
            
            // 上一页按钮
            const prevButton = document.createElement('button');
            prevButton.textContent = '上一页';
            prevButton.disabled = currentPage === 1;
            prevButton.onclick = () => {
                if (currentPage > 1) loadAssets(currentPage - 1);
            };
            pagination.appendChild(prevButton);
            
            // 页码按钮
            const maxVisiblePages = 5;
            let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
            let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
            
            if (endPage - startPage + 1 < maxVisiblePages) {
                startPage = Math.max(1, endPage - maxVisiblePages + 1);
            }
            
            if (startPage > 1) {
                const firstButton = document.createElement('button');
                firstButton.textContent = '1';
                firstButton.onclick = () => loadAssets(1);
                if (1 === currentPage) {
                    firstButton.classList.add('active');
                }
                pagination.appendChild(firstButton);
                
                if (startPage > 2) {
                    const ellipsis = document.createElement('span');
                    ellipsis.textContent = '...';
                    pagination.appendChild(ellipsis);
                }
            }
            
            for (let i = startPage; i <= endPage; i++) {
                const pageButton = document.createElement('button');
                pageButton.textContent = i;
                if (i === currentPage) {
                    pageButton.classList.add('active');
                }
                pageButton.onclick = () => loadAssets(i);
                pagination.appendChild(pageButton);
            }
            
            if (endPage < totalPages) {
                if (endPage < totalPages - 1) {
                    const ellipsis = document.createElement('span');
                    ellipsis.textContent = '...';
                    pagination.appendChild(ellipsis);
                }
                
                const lastButton = document.createElement('button');
                lastButton.textContent = totalPages;
                lastButton.onclick = () => loadAssets(totalPages);
                if (totalPages === currentPage) {
                    lastButton.classList.add('active');
                }
                pagination.appendChild(lastButton);
            }
            
            // 下一页按钮
            const nextButton = document.createElement('button');
            nextButton.textContent = '下一页';
            nextButton.disabled = currentPage === totalPages;
            nextButton.onclick = () => {
                if (currentPage < totalPages) loadAssets(currentPage + 1);
            };
            pagination.appendChild(nextButton);
        }
        
        // 通过ID查询资产（用于列表中的查看按钮）
        function queryAssetById(id) {
            document.getElementById('query-id').value = id;
            queryAsset();
            // 滚动到查询部分
            document.querySelector('.section:nth-child(2)').scrollIntoView({ behavior: 'smooth' });
        }
        
        // 辅助函数：显示错误信息
        function showError(elementId, message) {
            const element = document.getElementById(elementId);
            element.innerHTML = `
                <div class="error">${message}</div>
            `;
        }
        
        // 辅助函数：显示成功信息
        function showSuccess(elementId, message) {
            const element = document.getElementById(elementId);
            element.innerHTML = `
                <div class="success">${message}</div>
            `;
        }
        
        // 辅助函数：设置加载状态
        function setLoadingState(button, isLoading) {
            if (isLoading) {
                button.disabled = true;
                const loadingSpan = document.createElement('span');
                loadingSpan.className = 'loading';
                button.insertBefore(loadingSpan, button.firstChild);
                button.textContent = ' 处理中...';
            } else {
                button.disabled = false;
                const loadingSpans = button.querySelectorAll('.loading');
                loadingSpans.forEach(span => span.remove());
                // 恢复原始文本
                if (button.id === 'create-btn') {
                    button.textContent = '创建资产';
                } else if (button.id === 'query-btn') {
                    button.textContent = '查询资产';
                } else if (button.id === 'transfer-btn') {
                    button.textContent = '转移资产';
                } else if (button.parentNode.id === 'list-controls') {
                    button.textContent = '刷新列表';
                }
            }
        }
    </script>
</body>

</html>